package com.personal.baseDao;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;
/**
 * 
 * @author Liangwenjun
 * @version 1.1
 * {@link 243487992@qq.com}
 * @datetime 2017年6月27日14:37:18
 */
public class DaoGenDB {
		/**
		 * 读取默认配置文件
		 */
		public static Properties readPropertiesFile(){
			Properties pp = new Properties();
			try {
				FileInputStream fileInput = new FileInputStream("src/runtime-dev.properties");
				pp.load(fileInput);
				fileInput.close();
			} catch (FileNotFoundException e) {
				System.out.println("File of Properties was not found!!");
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return pp;
		}
		
		/**
		 * 获取数据库链接
		 * @return Connection 
		 */
		public static Connection getConn(){
			 Connection conn = null;
			 PreparedStatement pstmt = null;
			 
			Properties prop = readPropertiesFile();
			String driver = prop.getProperty("JDBC_DRIVER");
			String url = prop.getProperty("DB_URL");
			String userName = prop.getProperty("USER_NAME");
			String password = prop.getProperty("PASSWORD");
		
			try {
				Class.forName(driver);
				conn = DriverManager.getConnection(url, userName, password);
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return conn;
		}
		
		/**
		 * 
		 * @param sqlStr 传入的sql
		 * @return 返回删除的总行数，返回0 代表 没有数据
		 */
		public int deleteBySql(String sqlStr){
			Connection conn = null;
			 PreparedStatement pstmt = null;
			 
			int returnFlag = 0;
			try {
				conn = getConn();
				pstmt = conn.prepareStatement(sqlStr);
				returnFlag = pstmt.executeUpdate();
				conn.commit();
			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				try {
					if (pstmt != null) {
						pstmt.close();
					}
					if (conn != null) {
						conn.close();
					}
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			return returnFlag;
		}
}
